'use client'

import PageContainer from '@/components/PageContainer'
import type { UserListItem } from '@/hooks/useUser'
import { useUser } from '@/hooks/useUser'
import { DeleteOutlined, EditOutlined } from '@ant-design/icons'
import { Button, Form, Input, Modal, Popconfirm, Select, Space } from 'antd'
import { TablePaginationConfig } from 'antd/es/table'
import dayjs from 'dayjs'
import { useState } from 'react'

export default function UserPage() {
  const [open, setOpen] = useState(false)
  const [form] = Form.useForm()
  const [editingId, setEditingId] = useState<number | null>(null)
  const {
    loading,
    userList,
    pagination,
    setPagination,
    fetchUserList,
    saveUser,
    deleteUser,
    exportUserList,
    handleSearch,
    messageApi,
    contextHolder
  } = useUser()

  const columns = [
    {
      title: '用户名',
      dataIndex: 'username'
    },
    {
      title: '昵称',
      dataIndex: 'nickname'
    },
    {
      title: '邮箱',
      dataIndex: 'email'
    },
    {
      title: '性别',
      dataIndex: 'gender',
      render: (gender: string) =>
        ({
          male: '男',
          female: '女',
          unknown: '未知'
        }[gender])
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (status: string) =>
        ({
          online: '在线',
          offline: '离线'
        }[status])
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      render: (date: string) => dayjs(date).format('YYYY-MM-DD HH:mm:ss')
    },
    {
      title: '更新时间',
      dataIndex: 'updatedAt',
      render: (date: string) => dayjs(date).format('YYYY-MM-DD HH:mm:ss')
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_: any, record: UserListItem) => (
        <Space>
          <Button type="link" icon={<EditOutlined />} onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Popconfirm
            title="确定删除该用户吗？"
            onConfirm={() => deleteUser(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ]

  const handleAdd = () => {
    setOpen(true)
  }

  const handleEdit = (record: UserListItem) => {
    setEditingId(record.id)
    form.setFieldsValue(record)
    setOpen(true)
  }

  const handleCancel = () => {
    setEditingId(null)
    form.resetFields()
    setOpen(false)
  }

  const handleOk = async () => {
    try {
      const values = await form.validateFields()
      const { message } = await saveUser(values, editingId || undefined)

      messageApi.success(message)
      handleCancel()
      fetchUserList()
    } catch (errorMsg) {
      console.error(errorMsg as string)
    }
  }

  return (
    <>
      {contextHolder}
      <PageContainer
        title="用户管理"
        onAdd={handleAdd}
        tableProps={{
          columns,
          dataSource: userList,
          loading,
          pagination: {
            ...pagination,
            showSizeChanger: true,
            showTotal: total => `共 ${total} 条`,
            pageSizeOptions: ['10', '20', '50', '100'],
            showQuickJumper: true
          },
          onChange: (pagination: TablePaginationConfig) => {
            setPagination({
              current: pagination.current || 1,
              pageSize: pagination.pageSize || 10,
              total: pagination.total || 0
            })
            fetchUserList(pagination.current || 1, pagination.pageSize || 10)
          }
        }}
      >
        <Input.Search placeholder="搜索用户名/昵称/邮箱" onSearch={handleSearch} style={{ width: 250 }} allowClear />
        <Button type="default" onClick={exportUserList} loading={loading}>
          导出
        </Button>
      </PageContainer>

      <Modal
        title={editingId ? '编辑用户' : '新增用户'}
        open={open}
        onOk={handleOk}
        onCancel={handleCancel}
        maskClosable={false}
        width={'30vw'}
        centered
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            gender: 'unknown'
          }}
        >
          <Form.Item name="username" label="用户名" rules={[{ required: true, message: '请输入用户名' }]}>
            <Input placeholder="请输入用户名" />
          </Form.Item>

          <Form.Item name="nickname" label="昵称" rules={[{ required: true, message: '请输入昵称' }]}>
            <Input placeholder="请输入昵称" />
          </Form.Item>

          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '请输入有效的邮箱地址' }
            ]}
          >
            <Input placeholder="请输入邮箱" />
          </Form.Item>

          <Form.Item name="gender" label="性别">
            <Select>
              <Select.Option value="male">男</Select.Option>
              <Select.Option value="female">女</Select.Option>
              <Select.Option value="unknown">未知</Select.Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </>
  )
}
